package com.itheima.demo05JDBC事务_重点;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

public class Demo05 {
	public static void main(String[] args){
        Connection conn=null;
        Statement stmt=null;
        try {
            // 1.注册驱动(自动注册)
            // 2.获取连接
            conn = DriverManager.getConnection("jdbc:mysql:///day18", "root", "root");
            // 3.开启事务
            conn.setAutoCommit(false);
            // 4.获取到Statement
            stmt = conn.createStatement();
            // 5.Statement执行SQL

            String sql = "UPDATE account SET balance=balance-500 WHERE id=1;";
            int m=10/0;

            String sql1 = "UPDATE account SET balance=balance+500 WHERE id=2;";
            stmt.executeUpdate(sql);
            stmt.executeUpdate(sql1);
            conn.commit();
            System.out.println("成功提交事物");
            // 张三-500
            // 李四+500
        } catch (Exception throwables) {
            throwables.printStackTrace();
            try {
                conn.rollback();
                System.out.println("失败回滚事务");
            } catch (SQLException e) {
                e.printStackTrace();
            }

        }finally {
            if(stmt!=null){
                try {
                    stmt.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }

            }
            if(conn!=null){
                try {
                    conn.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }

        }

        // 6.成功提交事务
        // 6.失败回滚事务
    }
}
